package uodm.server;

import java.security.Principal;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import uodm.shared.model.AccessLog;
import uodm.shared.model.OfficeData;
import uodm.shared.model.UserData;

import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

public class Utils {

	static {
		ObjectifyService.register(OfficeData.class);
		ObjectifyService.register(UserData.class);
		ObjectifyService.register(AccessLog.class);
	}

	private Utils() {
	}

	public static Objectify ofy() {
		return com.googlecode.objectify.ObjectifyService.begin();
	}

	public static String getFullRequestUrl(HttpServletRequest req) {
		String part1 = req.getRequestURL().toString();
		String part2 = req.getQueryString();
		return part2 == null ? part1 : (part1 + "?" + part2);
		// String scheme = req.getScheme();
		// String server = req.getServerName();
		// String port = String.valueOf(req.getServerPort());
		// if (port == null) {
		// port = "";
		// } else {
		// port = ":" + port;
		// }
		// String path = req.getServletPath();
		// if (path == null) {
		// path = "";
		// }
		// String query = req.getQueryString();
		// if (query == null) {
		// query = "";
		// } else {
		// query = "?" + query;
		// }
		// return scheme + "://" + server + port + path + query;
	}

	public static void logAccess(HttpServletRequest req, String what) {
		AccessLog alog = new AccessLog();
		alog.setWhen(new Date());
		Principal p = req.getUserPrincipal();
		String who = null;
		if (p != null) {
			who = p.getName();
		}
		alog.setWho(who);
		alog.setSource(req.getRemoteAddr());
		alog.setDestination(getFullRequestUrl(req));
		alog.setWhat(getCurrentMethodName());
		// ofy().save().entity(alog);
		ofy().put(alog);
	}

	public static String getCurrentMethodName() {
		return Thread.currentThread().getStackTrace()[3].getMethodName();
	}

}
